﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace KaixinMobile.Forms
{
    using Kaixin;

    public partial class frmLogin : Form
    {
        private frmMain _parent = null;
        private bool _needCode = false;

        public frmLogin(frmMain parent)
        {
            InitializeComponent();
            _parent = parent;
        }

        private void SetCode(byte[] codedata)
        {
            if (codedata != null)
            {
                MemoryStream ms = new MemoryStream(codedata);
                pbCode.Image = new Bitmap(ms);
            }
        }

        private byte[] GetCode()
        {
            return _parent.ka.LoginGetCode();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            string user = cbUser.Text.Trim();
            string pass = tbPass.Text.Trim();
            string code = tbCode.Text.Trim();

            menuItem1.Enabled = false;
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;

            if (!user.Equals("") && !pass.Equals(""))
            {
                if (_parent != null)
                {
                    int ret;

                    if (!_needCode)
                        ret = _parent.ka.Login(user, pass);
                    else
                        ret = _parent.ka.LoginWithCode(user, pass, code);

                    if (ret == 1)
                        this.DialogResult = DialogResult.OK;
                    else if (ret == -1)
                    {
                        this.pnCode.Visible = true;
                        SetCode(GetCode());
                        _needCode = true;
                    }
                    else
                    {
                        if (MessageBox.Show(
                              "Login error, retry?", 
                               "Error", 
                               MessageBoxButtons.RetryCancel, 
                               MessageBoxIcon.Question,
                               MessageBoxDefaultButton.Button1)
                            == DialogResult.Cancel)
                            this.DialogResult = DialogResult.No;
                        else if (_needCode)
                            SetCode(GetCode());
                    }
                }
            }
            menuItem1.Enabled = true;
            Application.DoEvents();
            Cursor.Current = Cursors.Default;
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void pbCode_Click(object sender, EventArgs e)
        {
            SetCode(GetCode());
        }
    }
}